package com.pn.taikao.service.impl;

import com.pn.taikao.entity.Paper;
import com.pn.taikao.mapper.PaperMapper;
import com.pn.taikao.service.PaperService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PaperServiceImpl implements PaperService {

    private final PaperMapper paperMapper;

    public PaperServiceImpl(PaperMapper paperMapper) {
        this.paperMapper = paperMapper;
    }

    @Override
    public Long createPaper(Paper paper) {
        if (paper.getCreateTime() == null) {
            paper.setCreateTime(LocalDateTime.now());
        }
        if (paper.getUpdateTime() == null) {
            paper.setUpdateTime(LocalDateTime.now());
        }
        paperMapper.insert(paper);
        return paper.getId();
    }

    @Override
    public void updatePaper(Paper paper) {
        paper.setUpdateTime(LocalDateTime.now());
        paperMapper.update(paper);
    }

    @Override
    public void deletePaper(Long id) {
        paperMapper.deleteById(id);
    }

    @Override
    public Paper getById(Long id) {
        return paperMapper.selectById(id);
    }

    @Override
    public List<Paper> getByTeacherId(Long teacherId) {
        return paperMapper.selectByTeacherId(teacherId);
    }

    @Override
    public List<Paper> getByCourseId(Long courseId) {
        return paperMapper.selectByCourseId(courseId);
    }

    @Override
    public List<Paper> getPublishedByCourseId(Long courseId) {
        return paperMapper.selectPublishedByCourseId(courseId);
    }

    @Override
    public List<Paper> list(String name, Long teacherId, Long courseId, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return paperMapper.selectPage(name, teacherId, courseId, offset, size);
    }

    @Override
    public long count(String name, Long teacherId, Long courseId) {
        return paperMapper.count(name, teacherId, courseId);
    }

    @Override
    public void publishPaper(Long id) {
        paperMapper.updateStatus(id, "published");
    }

    @Override
    public void unpublishPaper(Long id) {
        paperMapper.updateStatus(id, "draft");
    }
}


